package jwei.apps.providers;

import java.util.HashMap;

import jwei.apps.db.ProductCache.ProductsCache;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class ProductContentProvider extends ContentProvider {

    private static final String TAG = "ProductContentProvider";

    private static final String DATABASE_NAME = "products_cache.db";

    private static final int DATABASE_VERSION = 2;

    private static final String PRODUCTS_TABLE_NAME = "products_cache";

    public static final String AUTHORITY = "jwei.apps.providers.ProductContentProvider";

    private static final UriMatcher sUriMatcher;

    private static final int PRODUCT = 1;

    private static final int PRODUCT_ID = 2;

    private static HashMap<String, String> projectionMap;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + PRODUCTS_TABLE_NAME + " (" + ProductsCache.PRODUCT_ID + " LONG PRIMARY KEY,"
                    + ProductsCache.PRODUCT_NAME + " VARCHAR(255)," + ProductsCache.BRAND_ID + " INTEGER,"
                    + ProductsCache.BRAND_NAME + " VARCHAR(255)," + ProductsCache.PRODUCT_URL + " VARCHAR(255),"
                    + ProductsCache.GENDER + " VARCHAR(255)," + ProductsCache.IMAGE_URL + " VARCHAR(255)" + " );");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + PRODUCTS_TABLE_NAME);
            onCreate(db);
        }
    }

    private DatabaseHelper dbHelper;

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#delete(android.net.Uri,
     * java.lang.String, java.lang.String[])
     */
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case PRODUCT:
                count = db.delete(PRODUCTS_TABLE_NAME, where, whereArgs);
                break;
            case PRODUCT_ID:
                String productId = uri.getPathSegments().get(1);
                count = db.delete(PRODUCTS_TABLE_NAME, ProductsCache.PRODUCT_ID + "=" + productId
                        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#getType(android.net.Uri)
     */
    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case PRODUCT:
                return ProductsCache.CONTENT_TYPE;
            case PRODUCT_ID:
                return ProductsCache.CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#insert(android.net.Uri,
     * android.content.ContentValues)
     */
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        if (sUriMatcher.match(uri) != PRODUCT) { throw new IllegalArgumentException("Unknown URI " + uri); }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert(PRODUCTS_TABLE_NAME, ProductsCache.PRODUCT, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(ProductsCache.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#onCreate()
     */
    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#query(android.net.Uri,
     * java.lang.String[], java.lang.String, java.lang.String[],
     * java.lang.String)
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
            case PRODUCT:
                qb.setTables(PRODUCTS_TABLE_NAME);
                qb.setProjectionMap(projectionMap);
                break;
            case PRODUCT_ID:
                qb.setTables(PRODUCTS_TABLE_NAME);
                qb.setProjectionMap(projectionMap);
                qb.appendWhere(ProductsCache.PRODUCT_ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.content.ContentProvider#update(android.net.Uri,
     * android.content.ContentValues, java.lang.String, java.lang.String[])
     */
    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case PRODUCT:
                count = db.update(PRODUCTS_TABLE_NAME, values, where, whereArgs);
                break;
            case PRODUCT_ID:
                String sermonId = uri.getPathSegments().get(1);
                count = db.update(PRODUCTS_TABLE_NAME, values, ProductsCache.PRODUCT_ID + "=" + sermonId
                        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, PRODUCTS_TABLE_NAME, PRODUCT);
        sUriMatcher.addURI(AUTHORITY, PRODUCTS_TABLE_NAME + "/#", PRODUCT_ID);

        projectionMap = new HashMap<String, String>();
        projectionMap.put(ProductsCache.PRODUCT_ID, ProductsCache.PRODUCT_ID);
        projectionMap.put(ProductsCache.IMAGE_URL, ProductsCache.IMAGE_URL);
        projectionMap.put(ProductsCache.PRODUCT_NAME, ProductsCache.PRODUCT_NAME);
        projectionMap.put(ProductsCache.BRAND_ID, ProductsCache.BRAND_ID);
        projectionMap.put(ProductsCache.PRODUCT_URL, ProductsCache.PRODUCT_URL);
        projectionMap.put(ProductsCache.GENDER, ProductsCache.GENDER);
        projectionMap.put(ProductsCache.BRAND_NAME, ProductsCache.BRAND_NAME);
    }
}
